package cn.gailvlun.gll.presentation.chat;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;

import com.github.markzhai.recyclerview.BaseViewAdapter;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import cn.gailvlun.gll.R;
import cn.gailvlun.gll.databinding.ActivityCheckCpBinding;
import cn.gailvlun.gll.net.HttpMethods;
import cn.gailvlun.gll.net.HttpSubscriber;
import cn.gailvlun.gll.net.ListRes;
import cn.gailvlun.gll.net.Member;
import cn.gailvlun.gll.presentation.base.BaseActivity;
import cn.gailvlun.gll.presentation.chat.adapter.CheckCpAdapter;
import cn.gailvlun.gll.presentation.chat.vm.Cp;
import cn.gailvlun.gll.util.DialogUtil;
import cn.gailvlun.gll.util.IsEmpty;
import cn.gailvlun.gll.util.RxUtil;
import cn.gailvlun.gll.widget.NavigationBarView;



public class CheckCpActivity extends BaseActivity implements OnRefreshListener, OnLoadmoreListener {

    public static final String EXTRA_ROOM_ID = "EXTRA_ROOM_ID";

    public static void openActivity(Context context, int roomId) {
        Intent intent = new Intent(context, CheckCpActivity.class);
        intent.putExtra(EXTRA_ROOM_ID, roomId);
        context.startActivity(intent);
    }

    private ActivityCheckCpBinding mBinding;
    private CheckCpAdapter mAdapter;
    private LinearLayoutManager mLayoutManager;
    private int mRoomId;

    @Override
    protected void initComponent() {
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_check_cp);

        mAdapter = new CheckCpAdapter(mContext);
        mAdapter.setPresenter(new Presenter());
        mBinding.recyclerView.setAdapter(mAdapter);

        mLayoutManager = new LinearLayoutManager(mContext);
        mBinding.recyclerView.setLayoutManager(mLayoutManager);

        mBinding.srl.setOnRefreshListener(this);
        mBinding.srl.setOnLoadmoreListener(this);
        mBinding.srl.setEnableLoadmore(false);

    }

    @Override
    protected void createHandler() {
        mBinding.nbv.setOnBackListener(new NavigationBarView.OnBackListener() {
            @Override
            public void onBack(NavigationBarView nb) {
                onBackPressed();
            }
        });

    }

    private Dialog pd;
    private RefreshReq req;

    @Override
    protected void loadData(@Nullable Bundle savedInstanceState) {
        pd = DialogUtil.showIndeterminate(mContext);
        mRoomId = getIntent().getIntExtra(EXTRA_ROOM_ID, -1);
        if (mRoomId == -1) {
            finish();
        }
        req = new RefreshReq();
        req.setmRoomId(mRoomId);

        getData(req);
    }

    private void pickupData(ListRes<Member> response) {
        List<Member> memberList = response.getResults();
        List<Member> memberCpList = response.getResults();
        for (Member member : memberList) {

            for (Member memberCp : memberCpList) {
                if (memberCp.isIs_host() || matchedCacheList.contains(member) || matchedCacheList.contains(memberCp)) {
                    continue;
                }
                if (memberCp.getId() == member.getCoupleId()) {
                    Cp cp = new Cp();
                    cp.setMember(member);
                    cp.setMemberCp(memberCp);
                    matchedCpList.add(cp);
                    matchedCacheList.add(member);
                    matchedCacheList.add(memberCp);
                    break;
                }
            }

            if (!member.isIs_host() && !matchedCacheList.contains(member)) {
                
                unMatchedCpList.add(member);
            }
        }
    }

    private List<Cp> matchedCpList = new ArrayList<>();
    private List<Member> unMatchedCpList = new ArrayList<>();
    private List<Member> matchedCacheList = new ArrayList<>();

    public void getData(@NonNull final RefreshReq req) {
        HttpMethods.getMemberService()
                .getMemberList(req.getmRoomId(), req.getPromise(), req.getId(), req.getDirection(), null)
                .compose(RxUtil.<ListRes<Member>>applyScheduler())
                .subscribe(new HttpSubscriber<ListRes<Member>>() {
                    @Override
                    protected void onSuccess(ListRes<Member> response) {
                        pd.dismiss();
                        mBinding.invalidateAll();
                        mBinding.srl.setEnableLoadmore(response.isNext());
                        if (response.getResults().size() > 0) {
                            int lastIndex = response.getResults().size() - 1;
                            req.setId(response.getResults().get(lastIndex).getId());
                            pickupData(response);
                        }

                        if (req.isLoadMore())

                        {
                            mAdapter.add(matchedCpList, CheckCpAdapter.Type.MATCHED_CONTENT.ordinal());
                            mAdapter.addAll(unMatchedCpList, CheckCpAdapter.Type.UN_MATCHED_CONTENT.ordinal());
                        } else

                        {
                            mBinding.invalidateAll();
                            mAdapter.clear();
                            if (IsEmpty.list(response.getResults())) {

                            } else {
                                if (!IsEmpty.list(matchedCpList)) {
                                    mAdapter.add(CheckCpAdapter.Type.MATCHED_HEADER, CheckCpAdapter.Type.MATCHED_HEADER.ordinal());
                                    mAdapter.addAll(matchedCpList, CheckCpAdapter.Type.MATCHED_CONTENT.ordinal());
                                }
                                if (!IsEmpty.list(unMatchedCpList)) {
                                    mAdapter.add(CheckCpAdapter.Type.UN_MATCHED_HEADER, CheckCpAdapter.Type.MATCHED_HEADER.ordinal());
                                    mAdapter.addAll(unMatchedCpList, CheckCpAdapter.Type.UN_MATCHED_CONTENT.ordinal());
                                }
                            }
                        }
                        mBinding.srl.finishLoadmore(0);
                        mBinding.srl.finishRefresh(200);

                    }

                    @Override
                    protected void onFailure(String errMsg, @Nullable ListRes<Member> response, int code) {
                        pd.dismiss();
                        DialogUtil.showError(mContext, errMsg);
                        mBinding.srl.finishLoadmore(0);
                        mBinding.srl.finishRefresh(200);
                    }
                });


    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        req.setLoadMore(true);
        getData(req);

    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        req.setLoadMore(false);
        getData(req);

    }

    class RefreshReq {
        private Integer mRoomId;
        private Integer id = 0;
        private Boolean isPromise = true;
        private String direction = "next";
        private boolean isLoadMore = false;

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public Integer getmRoomId() {
            return mRoomId;
        }

        public void setmRoomId(Integer mRoomId) {
            this.mRoomId = mRoomId;
        }

        public Boolean getPromise() {
            return isPromise;
        }

        public void setPromise(Boolean promise) {
            isPromise = promise;
        }

        public String getDirection() {
            return direction;
        }

        public void setDirection(String direction) {
            this.direction = direction;
        }

        public boolean isLoadMore() {
            return isLoadMore;
        }

        public void setLoadMore(boolean loadMore) {
            isLoadMore = loadMore;
            if (!loadMore) id = 0;
        }
    }


    public class Presenter implements BaseViewAdapter.Presenter {

    }

}
